package net.sf.midollo.task;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class MethodTask extends Task {

  protected Object target;
  protected Method method;

  public MethodTask(Object target, Method method, Object[] args) {
    super(args);
    this.method = method;
    this.target = target;
  }

  @SuppressWarnings("unchecked")
  public MethodTask(Object target, String methodName, Class[] types, Object[] args) throws NoSuchMethodException {
    this(target, null, args);
    Class clazz = target.getClass();
    if (target instanceof Class)
      this.target = null;
    this.method = clazz.getMethod(methodName, types);
  }

  protected Object execute(Object[] args) throws Throwable {
    try {
      return this.method.invoke(this.target, args);
    } catch (InvocationTargetException e) {
      throw e.getCause();
    }
  }
}
